package api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"server/global"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/WxOfficialAccount"
	"server/internal/pkg/response"
	"server/internal/services"
	"strings"
)

var LoginApi = new(loginApi)

// LoginApi 登录
type loginApi struct {
	model.User
}

// Router 路由
func (a loginApi) Router(r *gin.RouterGroup) {
	api := r.Group("/system")
	api.POST("/login", a.login)          //登录
	api.POST("/logout", a.logout)        //登录
	api.POST("/auth_login", a.authLogin) //微信授权登录

	api2 := r.Group("/system", middleware.LoginVerification)
	api2.GET("/index", a.index)
}

// Login	登录
// @Tags      登录
// @Accept       json
// @Summary   登录
// @Param model.User body  model.User true "用户名"
// @Produce   application/json
// @Success   200   "获取按钮全部列表"
// @Router    /api/v1/articles [post]
func (a loginApi) login(c *gin.Context) {
	type Param struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Success(c, "", err.Error())
		return
	}
	user := model.User{
		Username: param.Username,
		Password: param.Password,
	}
	user, ExpiresAt, err := services.Login.Login(c, user)

	user.ExpiresAt = ExpiresAt
	if err != nil {
		response.Error(c, err.Error(), err.Error())
		return
	} else {
		data := make(map[string]interface{})
		data["userinfo"] = user
		data["routePath"] = "/admin"
		response.Success(c, data, "登录成功")

	}

}

// Logout 退出登录
func (a loginApi) logout(c *gin.Context) {
	response.Success(c, "", "注销成功")
}

func (a loginApi) index(c *gin.Context) {
	userInfo, _ := c.Get("userInfo")

	Db := global.GL_DB
	type User struct {
		model.User
		Super bool `json:"super"`
	}

	user := services.User.GetById(userInfo.(model.User).ID)

	userToken := model.UserToken{}
	Db.Model(&userToken).Where("user_id=?", user.ID).First(&userToken)

	user.Token = userToken.Token
	user.ExpiresAt = userToken.ExpiresAt

	data := make(map[string]interface{})
	data["user_info"] = user

	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	data["menus"] = services.Menu.GetTreeList(0, rules, groupIds)

	siteConfig := make(map[string]interface{})
	detail := model.Config{}
	Db.Model(&detail).Where("`group` =?", "basics").First(&detail)
	map2 := make(map[string]interface{})
	json.Unmarshal([]byte(detail.Value), &map2)
	siteConfig["siteName"] = map2["siteName"]
	siteConfig["logo"] = map2["logo"]
	siteConfig["record_number"] = map2["record_number"]
	siteConfig["version"] = map2["version"]
	siteConfig["upload"] = map[string]string{
		"maxsize":  "10485760",
		"mimetype": "jpg,png,bmp,jpeg,gif,webp,zip,rar,xls,xlsx,doc,docx,wav,mp4,mp3,pdf,txt",
		"mode":     "local",
		"savename": "/storage/{topic}/{year}{mon}{day}/{filesha1}{.suffix}",
	}
	data["siteConfig"] = siteConfig
	data["terminal"] = map[string]string{"install_service_port": "8000", "npm_package_manager": "yarn"}
	response.Success(c, data, "")
}

func (a loginApi) test(c *gin.Context) {
	url := "http://open.cheegu.com/OCR.getVehicleLicense?token=8E4F8E02DCA844B589A5FE69C694CA1F"
	method := "POST"

	payload := strings.NewReader("imageUrl=https%3A%2F%2Ftaochewa.csjwlkj.cn%2Fuploads%2F20240529%2F523adb735ed992203ee85fd9f34473cd.png&side=0")

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("token", "0803b1cb-d84b-486d-ad53-929da8710d2f")
	req.Header.Add("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
	req.Header.Add("Accept", "*/*")
	req.Header.Add("Host", "open.cheegu.com")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))
}

// AuthLogin 微信授权登录
func (a loginApi) authLogin(c *gin.Context) {
	type Param struct {
		JsCode string `json:"js_code" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "", err.Error())
		return
	}

	login, err := WxOfficialAccount.AuthLogin(param.JsCode)
	if err != nil {
		response.Error(c, "", err.Error())
		return
	}

	user, ExpiresAt, err := services.Login.AuthLogin(c, login)

	user.ExpiresAt = ExpiresAt
	if err != nil {
		response.Error(c, "", err.Error())
		return
	} else {
		data := make(map[string]interface{})
		data["userinfo"] = user
		data["routePath"] = "/admin"
		response.Success(c, data, "登录成功")

	}

}
